var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var layout = require('express-layout');
var flash = require('connect-flash');
var passport = require('passport');
var	Strategy = require('passport-local').Strategy;
var	authorize = require('connect-ensure-login');

var index = require('./routes/index');
var users = require('./routes/users');
var other = require('./routes/other');
var face = require('./routes/face');
var db = require("./db/db.js");
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(layout());
app.use(cookieParser());
app.use(require('express-session')({
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
//app.set('layouts', './views/layouts');
app.set('layout', 'layout');
app.use(flash());

passport.use(new Strategy({
		usernameField: 'username',
		passwordField: 'password'
	},
	function(username, password, cb) {
		db.users.findByUsername(username, function(err, user) {
			if(err) {
				return cb(err);
			}
			if(!user) {
				return cb(null, false, {
					message: 'Incorrect username.'
				});
			}
			if(user.password != password) {
				return cb(null, false, {
					message: 'Incorrect password.'
				});
			}
			return cb(null, user);
		});
	}
));

passport.serializeUser(function(user, cb) {
	cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
	db.users.findById(id, function(err, user) {
		if(err) {
			return cb(err);
		}
		cb(null, user);
	});
});

//authorize.ensureLoggedIn()
app.use(function(req, res, next) {
	var deviceAgent = req.headers["user-agent"];
	var isMobile = deviceAgent.match(/(iphone|ipod|ipad|android)/i) != null ? true : false;
	res.locals.isMobile = isMobile;
	if(!req.isAuthenticated() && req.url.indexOf('login') == -1) {
		req.flash('error', 'You have to login first.');
		res.redirect("/login");
	} else {
		res.locals.user = req.user;
		next();
	}
})

app.use('/', index);
app.use('/user', users);
app.use('/other', other);
app.use('/face', face);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};
	console.log('Error: '+ req.url + ' '+err.message)
	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

module.exports = app;